#! python3
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''

import time,json,importlib
from com.zxy.common.Com_Fun import Com_Fun
from com.plugins.A01_9LK33T.Bus_Ope_DB_Cent import Bus_Ope_DB_Cent
from com.plugins.A01_9LK33T import A01_Para
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.common import Com_Para
from com.zxy.db2.Db_Common2 import Db_Common2
from com.zxy.comport.ComModBus import ComModBus
from com.plugins.A01_IHGDW0.monitor_data_model import monitor_data_model
from com.plugins.A01_9LK33T.HJpacket import HJpacket
from com.plugins.A01_IHGDW0.A01_Fun import A01_Fun
from com.zxy.z_debug import z_debug
class A01_9LK33T_Time(z_debug):
    strContinue      = "1"   
    strResult        = ""
    strIP            = ""
    strPort          = ""
    strSend          = ""
    def __init__(self):
        pass
    def init_start(self):
        temStrOT = ""
        try:
            bodc = Bus_Ope_DB_Cent()
            bodc.init_page()            
            uL = UsAdmin_Log(Com_Para.ApplicationPath, Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + "接收数据包==>"+self.strResult)
            uL.WriteLog()
            if self.strResult.find("\\\\r\\\\n") != -1 and  self.strResult.find("\\\\r\\\\n") != len(self.strResult) - 4:
                strA = self.strResult.split("\\r\\n")
            elif self.strResult.find("\\r\\n") != -1 and  self.strResult.find("\\r\\n") != len(self.strResult) - 2:
                strA = self.strResult.split("\r\n")
            else:
                strA = self.strResult.split("\r\n")
            for temStrOT in strA:
                if temStrOT == "" :
                    continue              
                temAry = temStrOT.replace("\r","").replace("\n","").split("&&")
                temCRCInit = temStrOT.replace("\r","").replace("\n","")  
                initPacket = HJpacket()
                initPacket.clear_value()       
                temHJpacket = HJpacket()
                temHJpacket.clear_value()
                temHeadAry = temCRCInit.replace("##","").split(";")
                for hn in temHeadAry:
                    if hn.split("=")[0].find("QN") == 4:
                        temHJpacket.attQN = hn.split("=")[1]
                        temHJpacket.attLength = hn.split("=")[0][0:4]
                    elif hn.split("=")[0] == "ST":
                        temHJpacket.attST = hn.split("=")[1]
                    elif hn.split("=")[0] == "CN":
                        temHJpacket.attCN = hn.split("=")[1]
                    elif hn.split("=")[0] == "PW":
                        temHJpacket.attPW = hn.split("=")[1]
                    elif hn.split("=")[0] == "MN":
                        temHJpacket.attMN = hn.split("=")[1]
                    elif hn.split("=")[0] == "Flag":
                        temHJpacket.attFlag = hn.split("=")[1]
                uL = UsAdmin_Log(Com_Para.ApplicationPath, Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + temStrOT)
                uL.SaveFileDaySub(temHJpacket.attMN)
                temHJpacket.attCP = temAry[1]
                temHJpacket.attCRC = temAry[2]
                if len(temCRCInit) > 10 :
                    temCRCInit = temCRCInit[6:len(temCRCInit) - 4]
                temCRC = temHJpacket.CheckCRC16Z(temCRCInit).upper()
                if temCRC != temHJpacket.attCRC:
                    uL = UsAdmin_Log(Com_Para.ApplicationPath, Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + "接收数据包错误CRC校验失败："+self.strResult)
                    uL.WriteLog()
                else:
                    self.ReleasePacket(self,temHJpacket)
        except Exception as e:
            temLog = ""
            if str(type(self)) == "<class 'type'>":
                temLog = self.debug_info(self)+temStrOT +"\r\n"+repr(e)
            else:
                temLog = self.debug_info()+temStrOT +"\r\n"+repr(e)
            uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
            uL.WriteLog()
    def ReleasePacket(self,inputHJpacket):
        temCPAry = inputHJpacket.attCP.split(";")
        temHtCP = {}
        temHtDev = {}
        temInfoId = {}
        for cpinfo in temCPAry:
            if cpinfo.find(",") != -1:
                iIndex = 0
                for cpv in cpinfo.split(","):                    
                    if iIndex == 0:
                        Com_Fun.SetHashTable(temHtCP,cpv.split("=")[0],cpv.split("=")[1])
                    else:
                        if cpv.split("=")[0] == "InfoId":
                            Com_Fun.SetHashTable(temInfoId,cpv.split("=")[1],cpv.split("=")[1])
                        Com_Fun.SetHashTable(temHtDev,cpv.split("=")[0],cpv.split("=")[1])
                        Com_Fun.SetHashTable(temHtCP,cpv.split("=")[0],cpv.split("=")[1])                   
                    iIndex = iIndex + 1
            elif len(cpinfo) > 1:
                Com_Fun.SetHashTable(temHtCP,cpinfo.split("=")[0],cpinfo.split("=")[1])
        temSock = None
        for temClientSocket in list(Com_Para.dServThreadList.keys()):
            if temClientSocket == self.strIP+"|"+self.strPort:
                temSock = Com_Para.dServThreadList[temClientSocket]
                break
        if inputHJpacket.attCN == "1000" and temSock is not None:
            try:
                pass
            except Exception as e:
                temLog = ""
                if str(type(self)) == "<class 'type'>":
                    temLog = self.debug_info(self)+repr(e)
                else:
                    temLog = self.debug_info()+repr(e)
                uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
                uL.WriteLog()
        elif inputHJpacket.attCN == "2011":
            self.ReleaseRealPacket(self,inputHJpacket,temHtCP,temSock)            
            pass
        elif inputHJpacket.attCN == "2051":
            self.ReleaseMinPacket(self,inputHJpacket,temHtCP,temSock)  
            pass
        elif inputHJpacket.attCN == "2061":
            self.ReleaseHourPacket(self,inputHJpacket,temHtCP,temSock)  
            pass
    def ReleaseRealPacket(self,inputHJpacket,temHtCP,temSock):        
        temmonitor_data_model = monitor_data_model()
        temt_station_info = None
        if inputHJpacket.attMN != "":
            for titems in A01_Para.ht_t_station_info:
                if inputHJpacket.attMN == titems.attMN_CODE:
                    temt_station_info = titems
                    temmonitor_data_model.station_code = temt_station_info.attSTATION_CODE
                    break;
        else:
            return None
        temDataTime = Com_Fun.GetHashTable(temHtCP,"DataTime")
        if len(temDataTime) == 14:
            temmonitor_data_model.get_time = temDataTime[0:4]+"-"+temDataTime[4:6]+"-"+temDataTime[6:8]+" "+temDataTime[8:10]+":"+temDataTime[10:12]+":"+temDataTime[12:14]
        else:
            return None
        for titems in A01_Para.ht_t_station_ele_link:
            if titems.attSTATION_CODE ==  temmonitor_data_model.station_code:
                temRtd = Com_Fun.GetHashTable(temHtCP,titems.attELEMENT_CODE+"-Rtd")
                if temRtd != "":
                    setattr(temmonitor_data_model,titems.attELEMENT_VAL.lower(),str(round(float(temRtd),titems.attDTO_NUM)))
        bodc = Bus_Ope_DB_Cent()
        bodc.upd_real(temmonitor_data_model)
        inputHJpacket.init_C_14_2()
        temReturn = inputHJpacket.GetSendPack()
        iR = Com_Fun.SendSocket(temReturn,temSock)
    def ReleaseMinPacket(self,inputHJpacket,temHtCP,temSock):
        temmonitor_data_model = monitor_data_model()
        temt_station_info = None
        if inputHJpacket.attMN != "":
            for titems in A01_Para.ht_t_station_info:
                if inputHJpacket.attMN == titems.attMN_CODE:
                    temt_station_info = titems
                    temmonitor_data_model.station_code = temt_station_info.attSTATION_CODE
                    break;
        else:
            return None
        temDataTime = Com_Fun.GetHashTable(temHtCP,"DataTime")
        if len(temDataTime) == 14:
            temmonitor_data_model.get_time = temDataTime[0:4]+"-"+temDataTime[4:6]+"-"+temDataTime[6:8]+" "+temDataTime[8:10]+":"+temDataTime[10:12]+":"+temDataTime[12:14]
        else:
            return None
        for titems in A01_Para.ht_t_station_ele_link:
            if titems.attSTATION_CODE ==  temmonitor_data_model.station_code:
                temRtd = Com_Fun.GetHashTable(temHtCP,titems.attELEMENT_CODE+"-Avg")
                if temRtd != "":
                    setattr(temmonitor_data_model,titems.attELEMENT_VAL.lower(),str(round(float(temRtd),titems.attDTO_NUM)))
        bodc = Bus_Ope_DB_Cent()
        if temmonitor_data_model.station_code != "":
            bodc.ins_minute(temmonitor_data_model)        
            inputHJpacket.init_C_14_2()
            temReturn = inputHJpacket.GetSendPack()
            iR = Com_Fun.SendSocket(temReturn,temSock)
    def ReleaseHourPacket(self,inputHJpacket,temHtCP,temSock):
        temmonitor_data_model = monitor_data_model()
        temt_station_info = None
        if inputHJpacket.attMN != "":
            for titems in A01_Para.ht_t_station_info:
                if inputHJpacket.attMN == titems.attMN_CODE:
                    temt_station_info = titems
                    temmonitor_data_model.station_code = temt_station_info.attSTATION_CODE
                    break;
        else:
            return None
        temDataTime = Com_Fun.GetHashTable(temHtCP,"DataTime")
        if len(temDataTime) == 14:
            temmonitor_data_model.get_time = temDataTime[0:4]+"-"+temDataTime[4:6]+"-"+temDataTime[6:8]+" "+temDataTime[8:10]+":"+temDataTime[10:12]+":"+temDataTime[12:14]
        else:
            return None
        for titems in A01_Para.ht_t_station_ele_link:
            if titems.attSTATION_CODE ==  temmonitor_data_model.station_code:
                temRtd = Com_Fun.GetHashTable(temHtCP,titems.attELEMENT_CODE+"-Avg")
                if temRtd != "":
                    setattr(temmonitor_data_model,titems.attELEMENT_VAL.lower(),str(round(float(temRtd),titems.attDTO_NUM)))
        if temmonitor_data_model.station_code != "":
            bodc = Bus_Ope_DB_Cent()
            bodc.ins_hour(temmonitor_data_model)
            inputHJpacket.init_C_14_2()
            temReturn = inputHJpacket.GetSendPack()
            iR = Com_Fun.SendSocket(temReturn,temSock)